<template>
  <l-layout class="l-tab-page pagecode" :topMove="false" :bottomMove="false">
    <template #top>
      <l-panel style="padding-bottom: 0">
        <div class="title">页面生成</div>
        <div class="steps">
          <el-steps :active="stepActive" simple finish-status="success">
            <el-step :title="$t('配置')"></el-step>
            <el-step :title="$t('表单')"></el-step>
            <el-step :title="$t('页面')"></el-step>
            <el-step :title="$t('菜单')"></el-step>
            <el-step :title="$t('预览')"></el-step>
          </el-steps>
        </div>
      </l-panel>
    </template>

    <l-layout v-show="steps(0)">
      <l-panel style="padding: 0; padding-left: 8px; padding-right: 8px">
        <div class="base-form-wraper" style="margin: auto; max-width: 800px">
          <el-form :model="formData" :rules="rules" size="mini" ref="baseInfo" label-width="80px">
            <el-col :span="24">
              <el-form-item label="功能名称" prop="name">
                <el-input v-model="formData.name" placeholder="需要与接口生成的功能名称一致"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="功能描述" prop="des">
                <el-input v-model="formData.des"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="功能模块" prop="area">
                <div class="l-rblock" style="padding-right: 64px">
                  <div class="l-rblock">
                    <l-select :options="devList" v-model="formData.area"></l-select>
                  </div>
                  <div class="l-select-btn">
                    <el-button @click="handleClickAreaOpen" size="mini" type="primary">添加</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>

            <div v-if="this.formData.formType == 1">
              <el-col :span="24">
                <el-form-item label="数据库" prop="dbCode">
                  <div class="l-rblock" style="padding-right: 64px">
                    <div class="l-rblock">
                      <el-select v-model="formData.dbCode" filterable placeholder="请选择">
                        <el-option-group v-for="group in lr_dblinkTree" :key="group.id" :label="group.label">
                          <el-option v-for="item in group.children" :key="item.id" :label="item.label" :value="item.id">
                          </el-option>
                        </el-option-group>
                      </el-select>
                    </div>
                    <div class="l-select-btn">
                      <el-button @click="handleClickDbOpen" size="mini" type="primary">添加</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="l-title">添加数据库表（请先选择数据库）</div>
              </el-col>
              <el-col :span="24">
                <l-edit-table
                  addBtnText="添加数据库表"
                  :dataSource="dbTableData"
                  @addRow="addRow"
                  @deleteRow="deleteRow"
                  highlight-current-row
                >
                  <el-table-column prop="type" label="类别" width="56" align="center">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.type == 'main'" size="mini">主表</el-tag>
                      <el-tag
                        @click="chlidTagClick(scope.row)"
                        v-else
                        size="mini"
                        style="cursor: pointer"
                        type="warning"
                        >子表</el-tag
                      >
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="表名" minWidth="100"> </el-table-column>
                  <el-table-column prop="comment" label="备注" minWidth="100"> </el-table-column>
                </l-edit-table>
              </el-col>
            </div>
          </el-form>
        </div>
      </l-panel>
    </l-layout>
    <div v-show="steps(1)" class="l-rblock">
      <l-form-design
        :dbTables="dbTableData"
        isNoScript
        isNotTopPadding
        isNotBottomPadding
        ref="formDesign"
      ></l-form-design>
    </div>
    <div v-show="steps(2)" class="l-rblock">
      <l-layout class="l-tab-page">
        <l-panel style="padding-top: 0; padding-bottom: 0">
          <div class="l-auto-window">
            <el-tabs v-model="configActiveName" :stretch="true">
              <el-tab-pane :label="$t('布局设置')" name="tab01">
                <pagecode-layout></pagecode-layout>
              </el-tab-pane>
              <el-tab-pane v-if="config.layoutType == 2" :label="$t('左侧树形设置')" name="tab05">
                <pagecode-lefttree :colslist="colslist"></pagecode-lefttree>
              </el-tab-pane>
              <el-tab-pane :label="$t('列表设置')" name="tab02">
                <pagecode-columns ref="columnsOp" :columnsTree="columnsTree"></pagecode-columns>
              </el-tab-pane>
              <el-tab-pane :label="$t('查询设置')" name="tab03">
                <pagecode-query ref="queryOp" :queryTree="queryTree"></pagecode-query>
              </el-tab-pane>
              <el-tab-pane :label="$t('按钮设置')" name="tab04">
                <pagecode-btns ref="btnOp"></pagecode-btns>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>
      </l-layout>
    </div>
    <div v-show="steps(3)" class="l-rblock">
      <pagecode-menu ref="menuform"></pagecode-menu>
    </div>
    <l-layout v-show="steps(4)" :left="320">
      <pagecode-code ref="code"></pagecode-code>
    </l-layout>

    <template #bottom>
      <l-panel style="padding-top: 0">
        <div class="leftbtns">
          <el-button @click="importScheme" size="mini">{{ $t("导入模版") }}</el-button>
          <el-button @click="loadDraft" size="mini">{{ $t("加载草稿") }}</el-button>
          <el-button @click="loadScheme" size="mini" type="success">{{ $t("加载模版") }}</el-button>
          <el-button @click="saveDraft" size="mini" type="warning">{{ $t("保存草稿") }}</el-button>
          <el-button @click="saveScheme" size="mini" type="primary" :disabled="stepSaveBtn">{{
            $t("保存模版")
          }}</el-button>
        </div>
        <div class="btns">
          <el-button @click="prev" size="mini" :disabled="stepPrevBtn">{{ $t("上一步") }}</el-button>
          <el-button @click="next" size="mini" :disabled="stepNextBtn" :loading="nextBtnLoading">{{
            $t("下一步")
          }}</el-button>
          <el-button @click="handleOk" size="mini" type="primary" :disabled="stepSaveBtn">{{
            $t("生成代码")
          }}</el-button>
        </div>
      </l-panel>
    </template>

    <!--数据库管理-->
    <l-drawer
      :title="$t('数据库管理')"
      :visible.sync="dbManagerVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <dblink-index></dblink-index>
    </l-drawer>
    <!--输出区域-->
    <l-drawer
      :title="$t('功能模块管理')"
      :visible.sync="areaManagerVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
      @closed="areaManagerClosed"
    >
      <area-index></area-index>
    </l-drawer>

    <!--数据表添加-->
    <l-codetable-selectdialog
      :visible.sync="dbtableSelectdialog"
      :dbCode="formData.dbCode"
      :isOkClose="false"
      @select="dbSelect"
    >
    </l-codetable-selectdialog>

    <!--加载草稿-->
    <l-dialog
      :title="$t('草稿加载')"
      :visible.sync="draftIndexVisible"
      :hasBtns="false"
      :width="800"
      :height="600"
      @opened="draftIndexOpened"
    >
      <draft-index ref="draftIndex" @load="draftLoad"></draft-index>
    </l-dialog>

    <!--保存草稿-->
    <l-dialog
      title="保存草稿"
      :visible.sync="draftFormVisible"
      :height="200"
      width="440px"
      @closed="draftFormClosed"
      @ok="draftSave"
    >
      <draft-form ref="draftForm"></draft-form>
    </l-dialog>

    <!--加载模版-->
    <l-dialog
      :title="$t('模版加载')"
      :visible.sync="schemeIndexVisible"
      :hasBtns="false"
      :width="1000"
      :height="600"
      @opened="schemeIndexOpened"
    >
      <scheme-index ref="schemeIndex" @load="schemeLoad"></scheme-index>
    </l-dialog>

    <!--保存模版-->
    <l-dialog
      title="保存模版"
      :visible.sync="schemeFormVisible"
      :height="200"
      :width="440"
      @closed="schemeFormClosed"
      @opened="schemeFormOpened"
      @ok="schemeSave"
    >
      <scheme-form ref="schemeForm"></scheme-form>
    </l-dialog>

    <!--导入模版-->
    <l-dialog
      :title="$t('导入模版')"
      :visible.sync="schemeImportVisible"
      :hasBtns="false"
      :width="1000"
      :height="600"
      @opened="schemeImportOpened"
    >
      <scheme-import ref="schemeImport" @load="schemeLoadImport"></scheme-import>
    </l-dialog>
  </l-layout>
</template>
<script>
import AreaIndex from "../area/index.vue";
import DblinkIndex from "../../../../core/modules/data/views/dblink/index.vue";
import DraftIndex from "./draftIndex.vue";
import DraftForm from "./draftForm.vue";
import SchemeIndex from "./schemeIndex.vue";
import SchemeForm from "./schemeForm.vue";
import SchemeImport from "./schemeImport.vue";

import pagecodeLayout from "./config/layout";
import pagecodeColumns from "./config/columns";
import pagecodeQuery from "./config/query";
import pagecodeBtns from "./config/btns";
import pagecodeLefttree from "./config/leftTree";
import pagecodeMenu from "./config/menu";
import pagecodeCode from "./config/code";

const apiCodeTable = window.$api.data.codeTable;
const apiProject = window.$api.codetool.project;
const apiModule = window.$api.system.moduleex;
const apiAppModule = window.$api.mapp.module;

import pathTree from "./pathTree";
export default {
  components: {
    AreaIndex,
    DblinkIndex,
    DraftIndex,
    DraftForm,
    SchemeIndex,
    SchemeForm,
    SchemeImport,
    pagecodeLayout,
    pagecodeColumns,
    pagecodeQuery,
    pagecodeBtns,
    pagecodeLefttree,
    pagecodeMenu,
    pagecodeCode,
  },
  provide() {
    return {
      pageCodeConfig: this.config,
    };
  },
  data() {
    return {
      lr_isPage: true,
      stepActive: 0,
      stepPrevBtn: true,
      stepNextBtn: false,
      stepSaveBtn: true,
      nextBtnLoading: false,

      draftIndexVisible: false,
      draftFormVisible: false,

      schemeIndexVisible: false,
      schemeFormVisible: false,
      schemeImportVisible: false,

      formData: {
        name: "",
        des: "",
        area: "",
        dbCode: "",
        formType: 2,
      },
      rules: {
        name: [
          { required: true, message: "请输入功能名称", trigger: "blur" },
          { pattern: /^[A-Za-z0-9_]+$/, message: "请输入英文数字或_" },
        ],
        area: [{ required: true, message: "请选择功能模块" }],
        //dbCode: [{ required: true, message: "请选择数据库", trigger: "change" }],
      },
      dbTableData: [],
      dbtableSelectdialog: false,
      tableColumns: {},
      selectTable: "",
      myColumns: [
        { prop: "name", label: "名称", minWidth: 120 },
        { prop: "coment", label: "备注", minWidth: 120 },
        { prop: "queryType", label: "查询方式", minWidth: 80, align: "center" },
        { prop: "isCodeRule", label: "单据编码", minWidth: 64, align: "center" },
      ],

      areaManagerVisible: false,
      devList: [],

      dbManagerVisible: false,

      // 配置信息
      configActiveName: "tab01",
      columnsTree: [
        {
          label: "全选",
          children: [],
        },
      ],
      queryTree: [
        {
          label: "全选",
          children: [],
        },
      ],
      config: {
        layoutType: 1,
        queryType: "1",
        btns: [
          { label: "新增", id: "Add", prop: "Add", icon: "el-icon-plus", isRowBtn: false },
          { label: "编辑", id: "Edit", prop: "Edit", isRowBtn: true },
          { label: "删除", id: "Delete", prop: "Delete", isRowBtn: true },
        ],
        left: {
          title: "左侧树形",
          colField: "",
          dataType: "1",
          dataIdKey: "",
          dataPIdKey: "",
          dataValueKey: "",
          dataLabelKey: "",
          colNames: [], // 数据源字段列表
          options: [], // 静态数据
          dataCode: "",
        },
        table: {
          isPage: true,
          columns: [],
          querys: [],
          sidx: "",
          isDESC: false,
        },
      },
      colslist: [],

      codePathTree: [],
      code: {},
      codeSelected: "",
      designDbTables: [],
    };
  },
  computed: {
    mySelectTableName() {
      if (this.dbTableData.length == 0) {
        return "";
      }
      const tableName = this.selectTable;
      if (this.$validatenull(tableName)) {
        return this.dbTableData.find((t) => t.type == "main").name;
      } else {
        return tableName;
      }
    },
    myFileds() {
      if (this.$validatenull(this.mySelectTableName)) {
        return [];
      } else {
        return this.dbTableData.find((t) => t.name == this.mySelectTableName).columns;
      }
    },
    codePathTtile() {
      if (!this.$validatenull(this.codeSelected) && !this.$validatenull(this.code[this.codeSelected])) {
        return this.code[this.codeSelected].path;
      } else {
        return "请选择预览代码";
      }
    },
    codeContent() {
      let res = "";
      if (this.codeSelected) {
        const code = this.code[this.codeSelected];
        if (code) {
          res = code.content;
        }
      }
      return res;
    },
  },
  created() {
    this.initData();
  },
  methods: {
    importScheme() {
      this.schemeImportVisible = true;
    },
    initData() {
      this.lr_loadDblink();
      this.getAreas();
    },

    // 步骤条设置
    steps(num) {
      return this.stepActive == num;
    },
    prev() {
      if (this.stepActive > 0) {
        this.stepActive--;
      }
      this.$nextTick(() => {
        this.updateBtnState();
      });
    },
    async next() {
      if (await this.myValidateSteps()) {
        if (this.stepActive < 4) {
          this.stepActive++;
        }
        this.$nextTick(() => {
          this.updateBtnState();
        });
      }
    },

    async myValidateSteps() {
      this.nextBtnLoading = true;
      if (this.validateSteps) {
        const res = await this.validateSteps(this.stepActive);
        this.nextBtnLoading = false;
        return res;
      }
      this.nextBtnLoading = false;
      return true;
    },
    updateBtnState() {
      this.stepSaveBtn = true;
      this.stepNextBtn = true;
      this.stepPrevBtn = true;
      switch (this.stepActive) {
        case 0:
          this.stepNextBtn = false;
          break;
        case 4:
          this.stepPrevBtn = false;
          this.stepSaveBtn = false;
          break;
        default:
          this.stepPrevBtn = false;
          this.stepNextBtn = false;
          break;
      }
    },
    async handleOk() {
      if (this.appConfig.online) {
        this.$message({
          type: "warning",
          message: "体验版本无法生成代码文件",
        });
      } else {
        // 生成代码文件
        const loading = this.$loading({
          lock: true,
          text: "代码生成中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        let list = this.$refs.code.getCode();
        if (list.length == 0) {
          this.$message({
            type: "warning",
            message: "请勾选需要生成的代码文件!",
          });
          loading.close();
          return;
        }

        const form = this.getForm();
        const wcode = {
          list,
          isPC: form.menu.isPC,
          isApp: form.menu.isApp,
          name: form.name,
          module: form.moduleId,
          moduleName: form.moduleName,
          modulePath: `${this.project.f_PCWeb}/src/modules/${this.$lowerFirst(form.moduleId)}`,
        };

        if (form.menu.isApp) {
          const pageJsonStr = await this.$awaitWraper(
            apiProject.getAppPageJson({ path: `${this.project.f_App}/pages.json` })
          );
          const pageJson = JSON.parse(pageJsonStr);
          let subPackage = pageJson.subPackages.find((t) => t.root == `pages${this.$upFirst(form.moduleId)}`);
          if (subPackage == undefined) {
            subPackage = {
              root: `pages${this.$upFirst(form.moduleId)}`,
              pages: [],
            };
            pageJson.subPackages.push(subPackage);
          }

          let isAppUpdate = false;
          list.forEach((item) => {
            if (item.isApp && subPackage.pages.findIndex((t) => t.path == item.route) == -1) {
              if (item.isQuery) {
                subPackage.pages.push({
                  path: item.route,
                  style: { navigationBarTitleText: item.name, navigationStyle: "custom" },
                });
              } else {
                subPackage.pages.push({
                  path: item.route,
                  style: { navigationBarTitleText: item.name },
                });
              }
              isAppUpdate = true;
            }
          });
          if (isAppUpdate) {
            wcode.pagejsPath = `${this.project.f_App}/pages.json`;
            wcode.pagejs = JSON.stringify(pageJson);
          }
        }

        const result = await apiProject.generatorWCode(wcode);
        this.downloadFile(result);
        // 注册菜单信息（所有配置信息）

        const menuDto = {
          baseInfo: {
            f_FullName: form.des,
            f_DeleteMark: 0,
            f_IsMenu: 1,
            f_ParentId: form.menu.f_ParentId || "0",
            f_Icon: form.menu.f_Icon,
            f_SortCode: 100,
            f_Target: "view",
            f_EnabledMark: 1,
            f_EnCode: `${form.moduleId}_${form.name}`,
            f_UrlAddress: `/${this.$lowerFirst(form.moduleId)}/${this.$lowerFirst(form.name)}/index`,
          },
          buttons: [],
          columns: [],
          forms: [],
        };

        // 移动端菜单信息注册
        const menuApp = {
          functionEntity: {
            f_Name: form.des,
            f_Type: form.menu.f_Type,
            f_Icon: form.menu.f_IconApp,
            f_Color: form.menu.f_Color,
            f_EnabledMark: 1,
            f_SortCode: 100,
            f_Url: `/pages${this.$upFirst(form.moduleId)}/${this.$lowerFirst(form.name)}/list`,
            f_IsSystem: 1,
            f_FormCode: "",
            f_FormVerison: "",
          },
          moduleItemEntitys: [],
        };

        // 按钮
        form.page.btns.forEach((btn, index) => {
          menuDto.buttons.push({ f_EnCode: btn.prop, f_FullName: btn.label, f_SortCode: index });

          if (btn.prop != "Export" && btn.prop != "Import") {
            menuApp.moduleItemEntitys.push({ f_Code: btn.prop, f_Name: btn.label, f_Type: 1 });
          }
        });
        // 表单
        let formMap = {};
        // 获取主表信息
        const mainTable = form.dbTable.find((t) => t.type == "main");
        form.formInfo.tabList.forEach((tab) => {
          tab.components.forEach((component) => {
            if (component.type == "gridtable") {
              menuDto.forms.push({
                f_EnCode: component.prop,
                f_FullName: "表格-" + component.label,
                f_SortCode: menuDto.forms.length,
              });
              component.children.forEach((gridcol) => {
                let gridProp = `${window.$lowerFirst(component.table)}|${gridcol.field}`;
                menuDto.forms.push({
                  f_EnCode: gridProp,
                  f_FullName: `${component.label || "表格"}-${gridcol.label}`,
                  f_SortCode: menuDto.forms.length,
                });
                menuApp.moduleItemEntitys.push({
                  f_Code: gridProp,
                  f_Name: `${component.label || "表格"}-${gridcol.label}`,
                  f_Type: 3,
                });
              });
            } else if (["btn"].includes(component.type)) {
              menuDto.forms.push({
                f_EnCode: component.prop,
                f_FullName: "按钮-" + component.label,
                f_SortCode: menuDto.forms.length,
              });
              menuApp.moduleItemEntitys.push({ f_Code: component.prop, f_Name: "按钮-" + component.label, f_Type: 3 });
            } else if (["divider"].includes(component.type)) {
              menuDto.forms.push({
                f_EnCode: component.prop,
                f_FullName: "线条-" + component.html,
                f_SortCode: menuDto.forms.length,
              });
              menuApp.moduleItemEntitys.push({ f_Code: component.prop, f_Name: "线条-" + component.html, f_Type: 3 });
            } else if (["viewtable"].includes(component.type)) {
              menuDto.forms.push({
                f_EnCode: component.prop,
                f_FullName: "表格-" + component.label,
                f_SortCode: menuDto.forms.length,
              });
              menuApp.moduleItemEntitys.push({ f_Code: component.prop, f_Name: "表格-" + component.label, f_Type: 3 });
            } else if (["card"].includes(component.type)) {
              menuDto.forms.push({
                f_EnCode: component.prop,
                f_FullName: "卡片-" + component.label,
                f_SortCode: menuDto.forms.length,
              });
            } else {
              //console.log(component.table,component.type,'component.table')
              let formProp = `${window.$lowerFirst(component.table)}_${window.$lowerFirst(component.field)}`;
              formMap[component.prop] = component;
              menuDto.forms.push({ f_EnCode: formProp, f_FullName: component.label, f_SortCode: menuDto.forms.length });
              menuApp.moduleItemEntitys.push({ f_Code: formProp, f_Name: component.label, f_Type: 3 });
            }
          });
        });
        // 列表
        form.page.table.columns.forEach((col, index) => {
          let colitem = formMap[col.prop];
          let colProp = "";
          if (mainTable.name == colitem.table) {
            colProp = window.$lowerFirst(colitem.field);
          } else {
            colProp = `${window.$lowerFirst(colitem.table)}_${colitem.field}`;
          }
          menuDto.columns.push({ f_EnCode: colProp, f_FullName: col.label, f_SortCode: index });
          menuApp.moduleItemEntitys.push({ f_Code: colProp, f_Name: col.label, f_Type: 2 });
        });

        if (form.menu.isApp && list.findIndex((t) => t.isApp) > -1) {
          await this.$awaitWraper(apiAppModule.add(menuApp));
        }

        if (form.menu.isPC && list.filter((t) => t.isApp).length < list.length) {
          await this.$awaitWraper(apiModule.add(menuDto));
        }

        loading.close();
        this.$message({
          type: "success",
          message: "代码生成成功",
        });
        this.reset();
      }
    },

    reset() {
      this.$formClear(this.$refs.baseInfo);
      this.dbTableData = [];
      this.$refs.formDesign.clear();
      this.$refs.menuform.resetForm();
      this.config.layoutType = 1;
      this.config.queryType = "1";
      this.config.btns = [
        { label: "新增", id: "Add", prop: "Add", icon: "el-icon-plus", isRowBtn: false },
        { label: "编辑", id: "Edit", prop: "Edit", isRowBtn: true },
        { label: "删除", id: "Delete", prop: "Delete", isRowBtn: true },
      ];

      this.config.left = {
        title: "左侧树形",
        colField: "",
        dataType: "1",
        dataIdKey: "",
        dataPIdKey: "",
        dataValueKey: "",
        dataLabelKey: "",
        colNames: [], // 数据源字段列表
        options: [], // 静态数据
        dataCode: "",
      };
      this.config.table = {
        isPage: true,
        columns: [],
        querys: [],
        sidx: "",
        isDESC: false,
      };
      this.configActiveName = "tab01";

      this.stepActive = 0;
      this.updateBtnState();
    },

    async validateSteps(stepActive) {
      if (stepActive == 0) {
        if (this.$validatenull(this.project.f_PCWeb) && this.$validatenull(this.project.f_App)) {
          this.$message({
            type: "error",
            message: "请在项目中设置前端PC项目地址 或者 移动端项目地址!",
          });
          return false;
        }
        if (!(await this.$formValidateWraper(this.$refs.baseInfo))) {
          return false;
        }

        if (this.formData.formType == 1) {
          if (this.dbTableData.length == 0) {
            this.$message({
              type: "error",
              message: "请添加数据库表!",
            });
            return false;
          }

          // 获取主表信息
          const mainTable = this.dbTableData.find((t) => t.type == "main");
          // 获取主表主键
          const mainKey = mainTable.columns.find((t) => t.isPrimary);
          if (!mainKey) {
            this.$message({
              type: "error",
              message: "主表没有主键无法生成代码!",
            });
            return false;
          }

          // 更新数据表
          this.$nextTick(() => {
            this.$refs.formDesign.updateTable();
          });
        } else {
          this.$refs.formDesign.setFormType(this.formData.formType);
        }
      } else if (this.stepActive == 1) {
        // 表单设计验证
        if (!this.$refs.formDesign.validate()) {
          return false;
        }
        let formScheme = this.$refs.formDesign.getData();
        let columns = [];
        formScheme.tabList.forEach((tab) => {
          columns.push(
            ...tab.components.filter(
              (t) => !["gridtable", "divider", "card", "password", "viewtable", "btn"].includes(t.type)
            )
          );
        });
        if (columns.length == 0) {
          this.$message({
            type: "error",
            message: `请设置组件,无法找到设置列的组件！`,
          });
          return false;
        }
        this.columnsTree[0].children = columns.map((t) => {
          return { id: t.prop, prop: t.prop, label: t.label, width: 120, align: "left", isMinWidth: false };
        });

        // 1.获取表格列
        // 2.过滤掉已选列中在表格列中找不到的列
        let columnsChecked = this.config.table.columns.filter(
          (t) => this.columnsTree[0].children.findIndex((t2) => t2.prop == t.prop) != -1
        );
        this.config.table.columns = columnsChecked;

        this.queryTree[0].children = columns
          .filter((t) => !["upload", "uploadimg", "layerbmap", "timerange", "datetimerange", "guid"].includes(t.type))
          .map((t) => {
            return { id: t.prop, prop: t.prop, label: t.label };
          });
        let queryChecked = this.config.table.querys.filter(
          (t) => this.queryTree[0].children.findIndex((t2) => t2.prop == t.prop) != -1
        );
        this.config.table.querys = queryChecked;

        this.colslist = columns.map((t) => {
          return { value: t.prop, label: t.label };
        });
        if (this.colslist.findIndex((t) => t.value == this.config.left.colField) == -1) {
          this.config.left.colField = "";
        }

        this.$nextTick(() => {
          this.$refs.columnsOp.setCheckedKeys(columnsChecked.map((t) => t.prop));
          this.$refs.queryOp.setCheckedKeys(queryChecked.map((t) => t.prop));
          this.$refs.btnOp.setCheckedKeys(this.config.btns.map((t) => t.id));
        });
        return true;
      } else if (this.stepActive == 2) {
        if (this.config.table.columns.length == 0) {
          this.$message({
            type: "error",
            message: `请设置列表列！`,
          });
          return false;
        }
        return true;
      } else if (this.stepActive == 3) {
        if (await this.$refs.menuform.validateForm()) {
          this.$refs.code.generatorCode(this.getSetting());
          return true;
        }
        return false;
      }
      return true;
    },

    // 第一步数据表设置
    addRow() {
      if (this.formData.dbCode) {
        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    deleteRow(data) {
      this.dbTableData.splice(data.index, 1);
      if (data.row.type == "main" && this.dbTableData.length > 0) {
        this.$set(this.dbTableData[0], "type", "main");
      }
    },
    chlidTagClick(row) {
      this.dbTableData.find((t) => {
        return t.type == "main";
      }).type = "chlid";
      row.type = "main";
      row.relationType = "";
      this.$set(this.dbTableData, 0, this.dbTableData[0]);
    },
    async dbSelect(list, showLoading, hideLoading) {
      showLoading("加载数据表中...");
      const tableList = [];
      const notAddTable = [];
      list.forEach((item) => {
        const table = {
          id: item.f_TableName,
          className: item.f_ClassName,
          name: item.f_TableName,
          comment: item.f_Description,
        };
        // 加载表的列信息
        if (this.tableColumns[table.name]) {
          table.columns = this.tableColumns[table.name];
        } else {
          table.columns = [];
          tableList.push(table);
        }

        if (this.dbTableData.length == 0) {
          table.type = "main";
          this.dbTableData.push(table);
        } else if (
          this.dbTableData.find((t) => {
            return t.name == table.name;
          }) == undefined
        ) {
          table.type = "chlid";
          this.dbTableData.push(table);
        } else {
          notAddTable.push(table.name);
        }
      });

      if (tableList.length > 0) {
        const codeTables = await this.$awaitWraper(
          apiCodeTable.getList(this.formData.dbCode, String(tableList.map((t) => t.name)))
        );
        for (const tableItem of tableList) {
          const codeTable = codeTables.find((t) => t.lr_db_codetableEntity.f_TableName == tableItem.name);
          this.$set(
            tableItem,
            "columns",
            codeTable.lr_db_codecolumnsList.map((t) => ({
              name: t.f_DbColumnName,
              csType: t.f_CsType,
              isIdentity: t.f_IsIdentity == 1,
              isPrimary: t.f_IsPrimaryKey == 1,
              isNullable: t.f_IsNullable == 1,
              coment: t.f_Description,
            }))
          );
        }
      }

      if (notAddTable.length > 0) {
        this.$message({
          message: `重复添加表【${String(notAddTable)}】`,
          type: "warning",
        });
      }

      this.dbtableSelectdialog = false;

      hideLoading();
    },

    // 功能模块
    handleClickAreaOpen() {
      this.areaManagerVisible = true;
    },
    areaManagerClosed() {
      this.getAreas();
    },
    async getAreas() {
      const data = await this.$awaitWraper(window.$api.codetool.area.getList());
      this.devList = (data || []).map((t) => {
        return { label: t.f_Label, value: t.f_Value };
      });
    },
    // 数据库链接
    handleClickDbOpen() {
      this.dbManagerVisible = true;
    },

    setForm(scheme) {
      // 设置模版信息
      this.formData.name = scheme.name;
      this.formData.des = scheme.des;
      this.formData.dbCode = scheme.dbCode;
      this.formData.db = scheme.db || [];
      this.formData.area = scheme.moduleId;
      this.dbTableData = scheme.dbTable;

      if (scheme.formType == 2) {
        this.formData.formType = scheme.formType;
        //this.designDbTables = scheme.designDbTables;
      }

      this.$refs.formDesign.setData(scheme.formInfo);
      if (scheme.page) {
        this.config.layoutType = scheme.page.layoutType;
        this.config.queryType = scheme.page.queryType;
        this.config.btns = scheme.page.btns;
        this.config.left = scheme.page.left;
        this.config.table = scheme.page.table;
      }
      if (scheme.menu) {
        this.$refs.menuform.setForm(scheme.menu);
      }
    },
    getForm() {
      // 获取模版信息
      const scheme = {
        db: this.formData.db,
        name: this.formData.name,
        des: this.formData.des,
        dbCode: this.formData.dbCode,
        moduleId: this.formData.area,
        moduleName: this.devList.find((t) => t.value == this.formData.area).label,
        dbTable: this.$deepClone(this.dbTableData),
        formInfo: this.$refs.formDesign.getData(),
        page: this.$deepClone(this.config),
        menu: this.$refs.menuform.getForm(),
      };

      return scheme;
    },
    // 获取配置信息
    // 代码生成
    getSetting() {
      // 获取配置信息
      const setting = {
        db: this.$deepClone(this.formData.db),
        name: this.formData.name,
        des: this.formData.des,
        dbCode: this.formData.dbCode,
        moduleName: this.devList.find((t) => t.value == this.formData.area).label,
        moduleId: this.formData.area,
        dbTable: this.$deepClone(this.dbTableData),
        formInfo: this.$refs.formDesign.getData(),
        page: this.$deepClone(this.config),
        menu: this.$refs.menuform.getForm(),
        userInfo: this.loginInfo,
        project: this.project,
        createTime: this.$getDayTime(),
        company: this.appConfig.company,
        codeTree: this.$deepClone(pathTree),
      };
      return setting;
    },

    // 草稿处理
    loadDraft() {
      this.draftIndexVisible = true;
    },
    saveDraft() {
      this.draftFormVisible = true;
    },
    async draftIndexOpened(showLoading, hideLoading) {
      showLoading("加载数据中...");
      await this.$refs.draftIndex.loadData();
      hideLoading();
    },
    draftFormClosed() {
      this.$refs.draftForm.resetForm();
    },
    async draftSave(showLoading, hideLoading) {
      if (await this.$refs.draftForm.validate()) {
        showLoading();
        await this.$refs.draftForm.save(JSON.stringify(this.getForm()));
        this.$message({
          type: "success",
          message: "保存草稿成功!",
        });
        hideLoading();
        this.draftFormVisible = false;
      }
    },
    draftLoad(row) {
      this.$nextTick(() => {
        var scheme = JSON.parse(row.f_Content);
        this.reset();
        this.draftIndexVisible = false;
        setTimeout(() => {
          this.setForm(scheme);
        });
      });
    },

    // 模版处理
    loadScheme() {
      this.schemeIndexVisible = true;
    },
    saveScheme() {
      this.schemeFormVisible = true;
    },
    async schemeIndexOpened(showLoading, hideLoading) {
      showLoading("加载数据中...");
      await this.$refs.schemeIndex.loadData();
      hideLoading();
    },

    async schemeImportOpened(showLoading, hideLoading) {
      showLoading("加载数据中...");
      await this.$refs.schemeImport.loadData();
      hideLoading();
    },
    schemeLoadImport(data) {
      this.$nextTick(() => {
        this.reset();
        this.schemeImportVisible = false;
        setTimeout(() => {
          this.setForm(data);
        });
      });
    },
    schemeLoad(row) {
      this.$nextTick(() => {
        var scheme = JSON.parse(row.f_Content);
        this.reset();
        this.schemeIndexVisible = false;
        setTimeout(() => {
          this.setForm(scheme);
        });
      });
    },
    async schemeFormOpened(showLoading, hideLoading) {
      showLoading("加载数据中...");
      await this.$refs.schemeForm.fetchSchemeTypes();
      hideLoading();
    },
    schemeFormClosed() {
      this.$refs.schemeForm.resetForm();
    },
    async schemeSave(showLoading, hideLoading) {
      if (await this.$refs.schemeForm.validate()) {
        showLoading();
        await this.$refs.schemeForm.save(JSON.stringify(this.getForm()));
        this.$message({
          type: "success",
          message: "保存模版成功!",
        });
        hideLoading();
        this.schemeFormVisible = false;
      }
    },
    downloadFile(file) {
      let blob = new Blob([file.data], { type: "application/zip" });
      let url = window.URL.createObjectURL(blob);
      let ele = document.createElement("a");
      ele.style.display = "none";
      ele.href = url;
      ele.download = `前端生成_${new Date().getTime()}`;
      document.body.appendChild(ele);
      ele.click();
      ele.remove();
      window.URL.revokeObjectURL(url);
    },
  },
};
</script>
<style lang="scss">
.pagecode {
  .title {
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 16px;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .steps {
    position: relative;
    margin: auto;
    height: 100%;
    width: 600px;
    text-align: center;

    .el-steps--simple {
      background: none;
      padding: 14px 8%;
    }
  }
  .btns {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    padding-right: 8px;
    display: flex;
    align-items: center;
  }
  .leftbtns {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    padding-left: 8px;
    display: flex;
    align-items: center;
  }
  .base-form-wraper {
    padding: 16px;
  }
  .l-select-btn {
    position: absolute;
    right: 0;
    top: 0;
    box-sizing: border-box;
  }
}
</style>
